<template>
  <div class="chat-container">
    <div class="chat-header">
      <div class="app-info">
        <div class="app-avatar">💕</div>
        <div class="app-details">
          <div class="app-title">AI恋爱大师</div>
          <div class="chat-id">会话ID: {{ chatId }}</div>
        </div>
      </div>
    </div>
    <div class="chat-history" ref="chatHistory">
      <div v-for="(msg, idx) in messages" :key="idx" :class="['chat-msg', msg.role]">
        <div class="msg-avatar" v-if="msg.role === 'ai'">💕</div>
        <div class="msg-content">
          <div class="msg-text">{{ msg.content }}</div>
        </div>
        <div class="msg-avatar user-avatar" v-if="msg.role === 'user'">👤</div>
      </div>
    </div>
    <div class="chat-input">
      <input 
        v-model="input" 
        @keyup.enter="sendMessage" 
        placeholder="输入你的情感困惑..." 
        class="input"
        :disabled="isLoading"
      />
      <button @click="sendMessage" class="btn btn-primary" :disabled="isLoading">
        <span v-if="!isLoading">发送</span>
        <span v-else class="loading-dots">发送中...</span>
      </button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import axios from 'axios'

const input = ref('')
const messages = ref([])
const chatId = ref('')
const chatHistory = ref(null)
const isLoading = ref(false)
let eventSource = null

// 根据环境变量设置 API 基础 URL
const API_BASE_URL = process.env.NODE_ENV === 'production'
  ? '/api' // 生产环境使用相对路径，适用于前后端部署在同一域名下
  : 'http://localhost:8123/api' // 开发环境指向本地后端服务

function genChatId() {
  return 'chat_' + Math.random().toString(36).slice(2) + Date.now()
}

function scrollToBottom() {
  nextTick(() => {
    if (chatHistory.value) {
      chatHistory.value.scrollTop = chatHistory.value.scrollHeight
    }
  })
}

function startSseWithMessage(msg) {
  isLoading.value = true
  // 关闭上一个 SSE
  if (eventSource) eventSource.close()
  // SSE 请求
  eventSource = new EventSource(`${API_BASE_URL}/ai/love_app/chat/sse?message=${encodeURIComponent(msg)}&chatId=${chatId.value}`)
  let aiMsg = { role: 'ai', content: '' }
  messages.value.push(aiMsg)
  eventSource.onmessage = (e) => {
    aiMsg.content += e.data
    // 强制触发响应式更新
    messages.value = [...messages.value]
    scrollToBottom()
  }
  eventSource.onerror = () => {
    eventSource.close()
    isLoading.value = false
  }
  eventSource.onclose = () => {
    isLoading.value = false
  }
}

onMounted(() => {
  chatId.value = genChatId()
})

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  scrollToBottom()
}, { deep: true })

function sendMessage() {
  if (!input.value.trim() || isLoading.value) return
  const userMsg = { role: 'user', content: input.value }
  messages.value.push(userMsg)
  const msg = input.value
  input.value = ''
  startSseWithMessage(msg)
}
</script>

<style scoped>
.chat-container {
  max-width: 800px;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  height: calc(100vh - 200px);
  border: 1px solid var(--border-color);
  border-radius: 16px;
  background: var(--card-bg);
  box-shadow: var(--shadow-card);
  overflow: hidden;
}

.chat-header {
  background: var(--darker-bg);
  border-bottom: 1px solid var(--border-color);
  padding: 1rem 1.5rem;
}

.app-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.app-avatar {
  width: 40px;
  height: 40px;
  background: var(--gradient-primary);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1.2rem;
  box-shadow: var(--shadow-glow);
}

.app-details {
  flex: 1;
}

.app-title {
  font-size: 1.1rem;
  font-weight: bold;
  color: var(--text-primary);
  margin-bottom: 0.25rem;
}

.chat-id {
  font-size: 0.85rem;
  color: var(--text-secondary);
}

.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
}

.chat-msg {
  display: flex;
  align-items: flex-start;
  gap: 0.75rem;
  max-width: 85%;
}

.chat-msg.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.chat-msg.ai {
  align-self: flex-start;
}

.msg-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 1rem;
  flex-shrink: 0;
}

.msg-avatar:not(.user-avatar) {
  background: var(--gradient-primary);
  box-shadow: 0 0 10px rgba(0, 212, 255, 0.3);
}

.user-avatar {
  background: var(--gradient-accent);
  box-shadow: 0 0 10px rgba(255, 107, 53, 0.3);
}

.msg-content {
  flex: 1;
  min-width: 0;
}

.msg-text {
  padding: 0.75rem 1rem;
  border-radius: 18px;
  background: var(--dark-bg);
  color: var(--text-primary);
  font-size: 0.95rem;
  line-height: 1.5;
  text-align: left;
  word-break: break-word;
  border: 1px solid var(--border-color);
}

.chat-msg.user .msg-text {
  background: var(--gradient-primary);
  color: white;
  border: none;
}

.chat-input {
  display: flex;
  gap: 1rem;
  padding: 1.5rem;
  border-top: 1px solid var(--border-color);
  background: var(--darker-bg);
}

.chat-input .input {
  flex: 1;
  padding: 0.75rem 1rem;
  border-radius: 12px;
  border: 2px solid var(--border-color);
  background: var(--card-bg);
  color: var(--text-primary);
  font-family: inherit;
  font-size: 0.95rem;
  transition: all 0.3s ease;
}

.chat-input .input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(0, 212, 255, 0.1);
}

.chat-input .input:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.chat-input .btn {
  padding: 0.75rem 1.5rem;
  border-radius: 12px;
  font-size: 0.95rem;
  font-weight: 600;
  min-width: 80px;
}

.chat-input .btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none !important;
}

.loading-dots {
  display: inline-block;
  position: relative;
}

.loading-dots::after {
  content: '';
  animation: dots 1.5s steps(4, end) infinite;
}

@keyframes dots {
  0%, 20% { content: ''; }
  40% { content: '.'; }
  60% { content: '..'; }
  80%, 100% { content: '...'; }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .chat-container {
    height: calc(100vh - 150px);
    margin: 0 1rem;
    border-radius: 12px;
  }
  
  .chat-header {
    padding: 1rem;
  }
  
  .chat-history {
    padding: 1rem;
    gap: 1rem;
  }
  
  .chat-msg {
    max-width: 90%;
  }
  
  .chat-input {
    padding: 1rem;
    gap: 0.75rem;
  }
  
  .msg-avatar {
    width: 32px;
    height: 32px;
    font-size: 0.9rem;
  }
  
  .msg-text {
    padding: 0.6rem 0.8rem;
    font-size: 0.9rem;
  }
}

@media (min-width: 769px) and (max-width: 1024px) {
  .chat-container {
    max-width: 700px;
  }
}
</style> 